package com.marketlive.app.b2c.account;

/*
(C) Copyright MarketLive. 2006. All rights reserved.
MarketLive is a trademark of MarketLive, Inc.
Warning: This computer program is protected by copyright law and international treaties.
Unauthorized reproduction or distribution of this program, or any portion of it, may result
in severe civil and criminal penalties, and will be prosecuted to the maximum extent
possible under the law.
*/

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
// struts imports
import org.apache.struts.action.*;
import org.apache.struts.actions.DispatchAction;
import org.marketlive.entity.account.IHint;
import org.marketlive.biz.session.context.ICommerceSession;
import org.marketlive.biz.account.IAccountManager;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sourcebeat.strutslive.formatter.Formatter;
import com.marketlive.app.b2c.WebUtil;
import com.marketlive.app.b2c.common.constants.ActionForwards;
import com.marketlive.app.b2c.common.constants.RequestParams;

/**
 * Dispatch action that checks state during registration process so that shoppers are taken to the correct page.
 * For details about parameters of methods please see the package description.
 */
public class AccountDispatcherAction  extends DispatchAction {
    private static Log log = LogFactory.getLog(AccountDispatcherAction.class);

    /** Spring injected. */
    private IAccountManager accountManager;
    /**
     * Default constructor.
     */
    public AccountDispatcherAction() {

    }

    /**
     * Sets object reference.  Spring injected.
     * @param accountManager
     */
    public void setAccountManager(IAccountManager accountManager) {
        this.accountManager = accountManager;
    }

    /**
     * Initialize formatters needed by AddressForm.jsp state and country drop down and QuestionAnswer.jsp hint
     * question drop down.
     */
    public void init() {
       
    }

    /**
     * Sets up registration/login page. Called from the link in TopNav.jsp.
     * For details about parameters of methods please see the package description.
     */
    public ActionForward start(ActionMapping mapping,
                               ActionForm form,
                               HttpServletRequest request,
                               HttpServletResponse response)
            throws Exception {

        //AccountRegisterForm accountRegisterForm = (AccountRegisterForm)
        //        request.getSession(false).getAttribute("accountRegisterForm");
        AccountRegisterForm accountRegisterForm = getAccountRegisterForm(request);

        if (accountRegisterForm != null) {
            if (accountRegisterForm.isLoggedIn() && (accountRegisterForm.isGuest() == false)) {
                log.debug("start() going to Account Gateway");
                return WebUtil.findForward(request, mapping, ActionForwards.GATEWAY_KEY);
            }
        }
        log.debug("start() mapping path " + mapping.getPath());
        return next(mapping, form, request, response);
    }

    /**
     * Forwards to next page in the process based on current state.
     * Please see package documentation for description of parameters.
     */
    public ActionForward next(ActionMapping mapping,
                              ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response)
            throws Exception {
        AccountRegisterForm accountRegisterForm = getAccountRegisterForm(request);

        if (canDoAccountGateway(accountRegisterForm)) {
            log.debug("  next() going to Account Gateway");
            return doAccountGateway(mapping, form, request, response);
        } else if (canDoRegisterAddress(accountRegisterForm)) {
            log.debug("  next() going to RegisterAddress");
            return doRegisterAddress(mapping,form,request,response);
        /*} else if (canDoRegisterUser(accountRegisterForm)) {
            log.debug("  next() going to RegisterUser");
            return doRegisterUser(mapping,form,request,response);
            */
        } else {
            log.debug("  next() going to login");
            return doLogin(mapping, form, request, response);
        }
    }

    /**
     * Forwards to the menu page Menu.jsp aka gateway.
     * Please see package documentation for description of parameters.
     */
    public ActionForward doAccountGateway(ActionMapping mapping,
                               ActionForm form,
                               HttpServletRequest request,
                               HttpServletResponse response)
            throws Exception {
        return WebUtil.findForward(request, mapping, ActionForwards.GATEWAY_KEY);
    }

    /**
     * Forwards to RegisterAddress.jsp.
     * Please see package documentation for description of parameters.
     */
    public ActionForward doRegisterAddress(ActionMapping mapping,
                                          ActionForm form,
                                          HttpServletRequest request,
                                           HttpServletResponse response)
            throws Exception {
        AccountRegisterForm accountRegisterForm = getAccountRegisterForm(request);
        // make sure its ok to show this page
        if (!canDoRegisterAddress(accountRegisterForm)) {
            return next(mapping, form, request, response);
        }
        return WebUtil.findForward(request, mapping, ActionForwards.REGISTER_ADDRESS_KEY);
    }

    /**
     * Forwards to RegisterUser.jsp
     * Please see package documentation for description of parameters.
     */
    public ActionForward doRegisterUser(ActionMapping mapping,
                               ActionForm form,
                               HttpServletRequest request,
                               HttpServletResponse response)
            throws Exception {
        return WebUtil.findForward(request, mapping, ActionForwards.REGISTER_USER_KEY);
    }

    /**
     * Forwards to the login page Login.jsp.
     * Please see package documentation for description of parameters.
     */
    public ActionForward doLogin(ActionMapping mapping,
                               ActionForm form,
                               HttpServletRequest request,
                               HttpServletResponse response)
            throws Exception {
        return WebUtil.findForward(request, mapping, ActionForwards.LOGIN_KEY);
    }

    /**
     * Returns true if can go to Account Gateway Page.
     * The only prerequisite is that the user successfully logged in as a returning customer.
     */
    public boolean canDoReturningCustomer(AccountRegisterForm accountRegisterForm) {
        return (accountRegisterForm.isReturningCustomerLoggedIn());
    }

    /**
     * Returns true if can go to Account Gateway Page.
     * The only prerequisite is that the user successfully registered or logged in.
     */
    public boolean canDoAccountGateway(AccountRegisterForm accountRegisterForm) {
        return (accountRegisterForm.isDoneWithRegistration() &&
                accountRegisterForm.isLoggedIn());
    }

    /**
     * Returns true if can go to Register Address Page.
     * The only prerequisite is that the user successfully registered.
     */
    public boolean canDoRegisterAddress(AccountRegisterForm accountRegisterForm) {
        return ( (accountRegisterForm.isDoneWithRegistration() == false) &&
                (accountRegisterForm.isReturningCustomer() == false) &&
                accountRegisterForm.isLoggedIn() &&
                (accountRegisterForm.isGuest() == false));
    }

    /**
     * Returns true if can go to Register User Page.
     * The only prerequisite is that the user is logged in.
     */
    public boolean canDoRegisterUser(AccountRegisterForm accountRegisterForm) {
        return accountRegisterForm.isLoggedIn();
    }

    /**
     * Utility to initialize the AccountRegisterForm.
     * @param request The HTTP request being processed.
     * @return
     * @throws Exception
     */
    public static AccountRegisterForm getAccountRegisterForm(HttpServletRequest request)
            throws Exception {
        ICommerceSession commerceSession = WebUtil.getCommerceSession(request);
        AccountRegisterForm bean = (AccountRegisterForm)
            request.getSession(false).getAttribute(RequestParams.ACCOUNT_FORM);

        if (bean == null) {
            // initialize new bean
            log.debug("creating new accountRegisterForm");
            bean = new AccountRegisterForm(commerceSession);
            request.getSession().setAttribute(RequestParams.ACCOUNT_FORM, bean);
        }

        // take care of the case where struts initializes with the no-arg constructor
        if (!bean.isInitialized()) {
            bean.initialize(commerceSession);
        }

        return bean;
    }
}
